#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import json
import logging
import os

from ksai.persistence.storage.attachment import Attachment
from ksai.serializer import serialize
from ksai.utils.paths import get_project_storage_path, to_path

logger = logging.getLogger(__name__)


def locate_metadata_filepath(attachment: Attachment):
    sign_path = to_path(attachment.sign)
    real_path = os.path.join(get_project_storage_path(), '_metadata', sign_path)
    filepath = os.path.join(real_path, 'metadata.json')
    return filepath


def read_metadata(attachment: Attachment) -> dict:
    filepath = locate_metadata_filepath(attachment)
    if os.path.isfile(filepath):
        with open(filepath, "r") as f:
            logger.debug("Reading metadata from file: {}".format(filepath))
            return json.load(f)
    return {}


def write_metadata(attachment: Attachment, metadata: dict):
    if metadata is None:
        metadata = {}

    uuids = metadata.get('uuids', [])
    if attachment.uuid not in uuids:
        uuids.append(attachment.uuid)

        filepaths = metadata.get('filepaths', [])
        if attachment.filepath not in filepaths:
            filepaths.append(attachment.filepath)

        original_filenames = metadata.get('original_filenames', {})
        names = original_filenames.get(attachment.original_name, [])
        if attachment.uuid not in names:
            names.append(attachment.uuid)
            original_filenames[attachment.original_name] = names

        attachment_metadata = {
            'sign': attachment.sign,
            'size': attachment.size,
            'mime': attachment.mime,
            'suffix': attachment.suffix,
            'uuids': uuids,
            'filepaths': filepaths,
            'original_filenames': original_filenames,
        }
        metadata.update(attachment_metadata)

        filepath = locate_metadata_filepath(attachment)
        parent_path = os.path.dirname(filepath)
        os.makedirs(parent_path, exist_ok=True)

        with open(filepath, "w") as f:
            logger.debug("Writing metadata to file: {}".format(filepath))
            json.dump(serialize(metadata), f, ensure_ascii=False)
